package com.x4sc.common.util;

import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class EnumLocale {

    private EnumLocale() {
        throw new IllegalAccessError("Utility class");
    }

    private static ResourceBundle getResourceBundle(Class<?> clazz, Locale locale) {
        return PropertyResourceBundle.getBundle(clazz.getName(), locale);
    }

    /*
    根据国际化名称取enum
    Locale can be get by LocaleContextHolder.getLocale();
    */
    public static <T extends Enum<T>> T getEnumByLocaleString(Class<T> clazz, String name, Locale locale) {
        ResourceBundle bundle = getResourceBundle(clazz, locale);
        if (bundle == null)
            return null;
        for (String key : bundle.keySet()) {
            if (bundle.getString(key).equals(name)) {
                return Enum.valueOf(clazz, key);
            }
        }
        return null;
    }

    /*
    取得enum的国际化名称
    Locale can be get by LocaleContextHolder.getLocale();
    */
    public static <T extends Enum<T>> String getLocalString(T e, Locale locale) {
        ResourceBundle bundle = getResourceBundle(e.getClass(), locale);
        if (bundle == null)
            return e.name();
        if (bundle.containsKey(e.name())) {
            return bundle.getString(e.name());
        }
        return "";
    }
}
